package com.dimeng.utils;

import android.os.Handler;
import android.os.Message;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-6-5 上午11:43:00<br>
 * descrition:下载远程数据线程
 */
public class LoadDataThread extends Thread{
	private String url;
	private Handler handler;
	private String charset;
	private boolean isOpenCache;
	/**
	 * @param url http资源url
	 * @param charset 字符编码
	 * @param handler 主线程的Handler对像，与主线程进行数据交换通讯
	 */
	public LoadDataThread(String url,String charset,Handler handler,boolean isOpenCache) {
		this.url = url;
		this.charset = charset;
		this.handler = handler;
		this.isOpenCache = isOpenCache;
	}
	
	@Override
	public void run() {
		int i = 0;
		Message msg = new Message();
		while(true) {
			try {
				if(++i == 2){//网络故障
					msg.what = 2;
					break;
				}
				String data = CommonUtil.getContent(url, charset,isOpenCache);
				if(data.length()>0) {//下载到数据
					msg.what = 1;
					msg.obj = data;
				} else {//远程无数据下载
					msg.what = 0;
				}
				break;
			} catch (Exception e) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
		handler.sendMessage(msg);
	}
}
